import { useRequest } from "ahooks"
import { Button, Cascader, Dropdown, Popover, Space, Table } from "antd"
import type { DQueryStationListParams } from "./service"
import { styled, history } from '@umijs/max'
import { useState } from "react";
import { queryCityOptions2 } from "@/services/common";
import { StationParkType, StationStatus, queryStationList } from "../station/stationList/services";
import type { Station } from "../station/stationList/services";
import { PAGINATION_CONFIG } from "@/constants";
import type { ColumnsType } from "antd/es/table/interface"
import { Card } from "@/components/Card"
import usePageAccess from "@/components/usePageAccess"
import Ellipsis from "@/components/Ellipsis";
import DetailModal from "../station/stationList/components/DetailModal";
import { jump2target } from "@/utils/common";

const Content = styled.div`
  width: 100%;
  height: 100%;
`

const StationMonitorCard: React.FC = () => {
  const access = usePageAccess()
  const [city, setCity] = useState<number[]>([])
  const [searchParams, setSearchParams] = useState<DQueryStationListParams>({
    pageNum: 1, pageSize: 10,
  });
  const cityOptions = useRequest(queryCityOptions2)
  const stationList = useRequest(() => queryStationList({...searchParams, cityId: city?.[2]}), {
    refreshDeps: [searchParams],
  })
  const [detailId, setDetailId] = useState<string>()

  const openEquipmentPage = (record: Station) => {
    jump2target(`/station/stubList?stationId=${record.id}&stationName=${record.stationName}`, {needRefresh: true})
  }

  const openEditPage = (title: string, type: string, id?: string) => {
    jump2target(`/station/stationList/edit?type=${type}&id=${id || ''}`, {needRefresh: true})
    sessionStorage.setItem('__/station/stationList/edit_title', title)
  }

  const openDetailModal = (record: Station) => {
    setDetailId(record.id)
  }

  const onDetailModalCancel = () => {
    setDetailId(undefined)
  }

  const doSearch = () => {
    setSearchParams({
      pageNum: 1,
      pageSize: searchParams.pageSize,
    })
  }

  const columns: ColumnsType<Station> = [
    {
      title: '场站名称',
      dataIndex: 'stationName',
    },
    {
      title: '场站地址',
      dataIndex: 'address',
      render: val => val && <Popover content={val}>
        <Ellipsis>{val}</Ellipsis>
      </Popover>
    },
    {
      title: '经销商',
      dataIndex: 'orgName',
      width: 140,
      render: val => val || '--',
    },
    {
      title: '直流枪数',
      dataIndex: 'acNum',
      width: 90,
    },
    {
      title: '交流枪数',
      dataIndex: 'dcNum',
      width: 90,
    },
    {
      title: '额定功率(kW)',
      dataIndex: 'kw',
      width: 130,
    },
    {
      title: '停车费',
      dataIndex: 'parkType',
      width: 90,
      render: val => val && StationParkType[val]
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 90,
      render: val => StationStatus[val],
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 140,
      render: (_, record) => {
        let actions: {key: string, node: React.ReactNode}[] = []
        let menus: {label: React.ReactNode, key: string}[] = []
        if (access.basicInfo || true) actions.push({key: 'basicInfo', node: <a key='basicInfo' onClick={() => openDetailModal(record)}>详情</a>})
        if (access.relevanceDevice || true) actions.push({key: 'relevanceDevice', node: <a key='relevanceDevice' onClick={() => openEquipmentPage(record)}>设备列表</a>})

        // 超过 3 个按钮，多余的按钮缩略展示
        actions = actions.filter((item, index) => {
          if (index < 3) return true
          menus.push({label: item.node, key: item.key})
          return false
        })
        
        if (menus.length) {
          const onClick = (v: any) => {
            switch (v.key) {
              case 'edit': openEditPage('编辑场站', 'edit', record.id); break;
            }
          }
          actions.push({
            key: 'dropdown', 
            node: <Dropdown key='dropdown' menu={{ items: menus, onClick }}>
              <a>...</a>
            </Dropdown>
          })
        }
        
        return (
          <Space>{actions.map(it => it.node)}</Space>
        )
      }
    },
  ]

  const onCityChange = (value: any) => {
    setCity(value)
  }

  return <Card
    className="row"
    header='站点实时监控'
  >
    <Content>
      <Space style={{paddingBottom: 20}}>
        <span>选择城市:</span>
        <Cascader
          loading={cityOptions.loading}
          options={cityOptions.data?.data}
          style={{width: 320}}
          placeholder='请选择'
          value={city}
          onChange={onCityChange}
        />
        <Button type="primary" onClick={doSearch} loading={stationList.loading}>查询</Button>
      </Space>
      <Table<Station>
        rowKey='id'
        loading={stationList.loading}
        dataSource={stationList.data?.data}
        columns={columns}
        scroll={{y: 400}}
        pagination={{
          ...PAGINATION_CONFIG,
          current: searchParams.pageNum,
          pageSize: searchParams.pageSize,
          total: stationList.data?.totalCount || 0,
          onChange: (page, pageSize) => {
            setSearchParams({
              ...searchParams,
              pageNum: page === searchParams.pageNum ? 1 : page,
              pageSize,
            })
          }
        }}
      />
    </Content>
    <DetailModal
      id={detailId}
      onCancel={onDetailModalCancel}
    />
  </Card>
}

export default StationMonitorCard